<template>
  <div class="np-input-search" :class="{ 'is-clear': clearable, 'is-search': searchable }">
    <el-input v-model="inputValue" :placeholder="placeholder" @input="handleInput" @keyup.enter.native="handleEnter" />
    <span class="mp-input__suffix">
      <div v-if="clearable" @click="handleClear">
        <np-svg-icon icon-class="all-input-clear" :w-h="['14px']" />
      </div>
      <div v-if="searchable" @click="handleSearch">
        <np-svg-icon icon-class="all-input-search" :w-h="['14px']" />
      </div>
    </span>
  </div>
</template>
<script>
export default {
  name: 'NpInputSearch',
  props: {
    value: {
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    searchable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      inputValue: '',
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.inputValue = newVal ? newVal : ''
      }
    },
  },
  methods: {
    handleInput(e) {
      this.$emit('input', this.inputValue)
    },
    handleClear(e) {
      this.inputValue = ''
      this.handleInput()
      this.$emit('clear', e)
      this.handleAllSearch(e, 'clear')
    },
    handleSearch(e) {
      this.$emit('search', e)
      this.handleInput()
      this.handleAllSearch(e, 'search')
    },
    handleEnter(e) {
      this.$emit('enter', e)
      this.handleInput()
      this.handleAllSearch(e, 'enter')
    },
    handleAllSearch(e, type) {
      /**
       * @e 每次动作的原始参数
       * @type 每次动作的类型,总共有 [clear, search, enter]
       */
      this.$emit('all-search', e, type)
      this.handleInput()
    },
  }
}
</script>
<style scoped lang="scss">
.np-input-search {
  position: relative;

  &:hover {
    .mp-input__suffix {
      &>div {
        color: #C27B55;
      }
    }
  }

  &:focus-within {
    .mp-input__suffix {
      &>div {
        color: #312114;
      }
    }
  }

  @mixin com-is {
    .el-input__inner {
      padding-right: 40px;
    }
  }

  &::v-deep {
    &.is-clear {
      @include com-is;

      &.is-search {
        .el-input__inner {
          padding-right: 64px;
        }
      }
    }

    &.is-search {
      @include com-is;
    }
  }

  .mp-input__suffix {
    position: absolute;
    height: 100%;
    right: 0px;
    top: 0;
    display: flex;
    align-items: center;
    pointer-events: none;
    margin-right: 16px;

    &>div {
      cursor: pointer;
      pointer-events: auto;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 4px;
      padding: 4px;
      border-radius: 50%;
      color: #8B8B8B;

      &:hover {
        color: #312114;
      }

      &:first-child {
        margin-left: 0;
      }
    }
  }
}
</style>